package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpSellerStoreGroup;
import com.erp.gather.domain.ErpSellerStoreProductGroup;
import com.erp.gather.domain.bo.ErpSellerStoreProductGroupBo;
import com.erp.gather.domain.vo.ErpSellerStoreProductGroupVo;
import com.erp.gather.mapper.ErpSellerStoreGroupMapper;
import com.erp.gather.mapper.ErpSellerStoreProductGroupMapper;
import com.erp.gather.mapper.ErpSellerStoreProductMapper;
import com.erp.gather.service.IErpSellerStoreProductGroupService;
import com.ruoyi.ae.api.RemoteAeStoreGroupService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.gather.api.domain.dto.SendProductGroupDto;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户店铺商品分组关联Service业务层处理
 *
 * @author erp
 * @date 2023-11-08
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreProductGroupServiceImpl implements IErpSellerStoreProductGroupService {
    @Autowired
    RestTemplate restTemplate;
    @Resource
    RemoteAeStoreGroupService remoteAeStoreGroupService;

    private final ErpSellerStoreProductGroupMapper baseMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final ErpSellerStoreGroupMapper erpSellerStoreGroupMapper;


    /**
     * 查询用户店铺商品分组关联
     */
    @Override
    public ErpSellerStoreProductGroupVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户店铺商品分组关联列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreProductGroupVo> queryPageList(ErpSellerStoreProductGroupBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreProductGroup> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreProductGroupVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户店铺商品分组关联列表
     */
    @Override
    public List<ErpSellerStoreProductGroupVo> queryList(ErpSellerStoreProductGroupBo bo) {
        LambdaQueryWrapper<ErpSellerStoreProductGroup> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreProductGroup> buildQueryWrapper(ErpSellerStoreProductGroupBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreProductGroup> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGroupId() != null, ErpSellerStoreProductGroup::getGroupId, bo.getGroupId());
        lqw.eq(bo.getSellerStoreProductId() != null, ErpSellerStoreProductGroup::getSellerStoreProductId, bo.getSellerStoreProductId());
        lqw.eq(bo.getStatus() != null, ErpSellerStoreProductGroup::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreProductGroup::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增用户店铺商品分组关联
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreProductGroupBo bo) {
        ErpSellerStoreProductGroup add = BeanUtil.toBean(bo, ErpSellerStoreProductGroup.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户店铺商品分组关联
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreProductGroupBo bo) {
        ErpSellerStoreProductGroup update = BeanUtil.toBean(bo, ErpSellerStoreProductGroup.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreProductGroup entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户店铺商品分组关联
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public R<Object> bindingProdudtForGroup(String productIds, Long groupId) {
//        List<String> list = Arrays.asList(productId.split(","));
//        StringBuffer productGroups = new StringBuffer();

        ErpSellerStoreGroup group = erpSellerStoreGroupMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getGroupId, groupId));
        if (ObjectUtils.isEmpty(group)) {
            return R.fail("该分组不存在");
        }

        //查看该分组下是否还有其他分组
        List<ErpSellerStoreGroup> groupList = erpSellerStoreGroupMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getParentId, groupId)
        );
        if (groupList.size() > 0) {
            return R.fail("该分组不为叶子结点（有其他分组），不能直接向该分组下添加商品");
        }

//        int i = 0;
//        for (String id : list) {
//            //查看这个商品是否存在
//            ErpSellerStoreProduct product = erpSellerStoreProductMapper.selectById(id);
//            if (ObjectUtils.isEmpty(product)) {
////                return R.fail("商品不存在");
//                continue;
//            }
//
//            //若其他分组有该商品，则转为-1
////            List<ErpSellerStoreProductGroup> productGroupOtherList = baseMapper.selectList(
////                    new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
////                            .eq(ErpSellerStoreProductGroup::getSellerStoreProductId, id)
////                            .ne(ErpSellerStoreProductGroup::getStatus, -1)
////            );
////            if (productGroupOtherList.size() > 0) {
////                for (ErpSellerStoreProductGroup productGroupOther : productGroupOtherList) {
////                    productGroupOther.setStatus(-1);
////                    baseMapper.updateById(productGroupOther);
////                }
////            }
//
//            ErpSellerStoreProductGroup productGroup = baseMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
//                            .eq(ErpSellerStoreProductGroup::getGroupId, groupId)
//                            .eq(ErpSellerStoreProductGroup::getSellerStoreProductId, id)
////                            .eq(ErpSellerStoreProductGroup::getStatus, 0)
//            );
//            ErpSellerStoreProductGroup productGroupNew = new ErpSellerStoreProductGroup();
//            if (ObjectUtils.isNotNull(productGroup)) {
//                productGroupNew.setId(productGroup.getId());
//            }
//            productGroupNew.setGroupId(groupId);
//            productGroupNew.setAeProductId(product.getAeProductId());
//            productGroupNew.setSellerStoreProductId(Long.valueOf(id));
//            productGroupNew.setStatus(0);
//            baseMapper.insertOrUpdate(productGroupNew);
//            productGroups.append(productGroupNew.getAeProductId().toString());
//            productGroups.append(",");
//            i++;
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("productGroups", productIds);
        map.put("storeId", group.getStoreId().toString());
        map.put("groupId", group.getGroupId().toString());

        return R.ok(map);
    }

    @Override
    @Async
    public void sendProductGroupToAe(Map<String,Object> dto) {


        //添加该商品到速卖通分组中
//        R<Object> objectR = remoteAeStoreGroupService.bindingProdudtForGroup(dto);
//        System.out.println(objectR);
        //TODO AE内部类
//        JSONObject data = JSONObject.parseObject((String) objectR.getData());
//        System.out.println(data);
//        Map<String, Object> productMap = (Map<String, Object>) data.get("productMap");
//        String groupId = (String) data.get("groupId");

//        for (String key : productMap.keySet()) {
//            ErpSellerStoreProductGroup productGroup = baseMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
//                            .eq(ErpSellerStoreProductGroup::getAeProductId, key)
//                            .eq(ErpSellerStoreProductGroup::getGroupId, groupId)
//            );
//            if (ObjectUtils.isNotEmpty(productGroup)) {
//                if (productMap.get(key).equals("false")){
//                    productGroup.setStatus(2);
//                }else {
//                    //同步成功
//                    productGroup.setStatus(1);
//                }
//                baseMapper.updateById(productGroup);
//            } else {
//                continue;
//            }
//        }
    }

    @Override
    public R<Object> synchronizeProductGroup(String groupId) {
        int count = 0;
        ErpSellerStoreGroup group = erpSellerStoreGroupMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getGroupId, groupId)
        );
        if (ObjectUtils.isEmpty(group)) {
            return R.fail("分组不存在");
        }
        //确认该分组是否为叶子节点分组
        List<ErpSellerStoreGroup> groupList = erpSellerStoreGroupMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getParentId, groupId)
        );
        if (groupList.size() > 0) {
            return R.fail("该分组不为叶子结点（有其他分组），无法同步");
        }

        //查找分组下商品
        List<ErpSellerStoreProductGroup> productGroups = baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
                        .eq(ErpSellerStoreProductGroup::getGroupId, groupId)
                        .eq(ErpSellerStoreProductGroup::getStatus, 1)
        );
        System.out.println(productGroups);

        Set<Long> ids = productGroups.stream()
                .map(ErpSellerStoreProductGroup::getAeProductId)    // 抽出每个ErpSellerStoreProductGroup对象的id
                .collect(Collectors.toSet());   // 创建新的集合
        if (ids.size() == 0) {
            return R.ok("分组内无商品不需要同步");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", group.getStoreId().toString());
        map.put("groupId", group.getGroupId().toString());
        map.put("ids", ids);

        //TODO 改造为Ae调用
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/productGroup/queryProductGroupIdByProductId", map, String.class);
//        String body = forEntity.getBody();
//        JSONObject jsonObject = JSONObject.parseObject(body).getString("data");
        R<Object> objectR = remoteAeStoreGroupService.queryProductGroupIdByProductId(map);
        String body = objectR.getData().toString();

        Map<String, Object> returnMap = (Map<String, Object>) JSONObject.parseObject(body).get("data");
        for (String key : returnMap.keySet()) {
            ErpSellerStoreProductGroup productGroup = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
                            .eq(ErpSellerStoreProductGroup::getAeProductId, key)
                            .eq(ErpSellerStoreProductGroup::getGroupId, groupId)
                            .eq(ErpSellerStoreProductGroup::getStatus, 1)
            );
            if (ObjectUtils.isEmpty(productGroup)) {
                productGroup.setStatus(-1);
                baseMapper.updateById(productGroup);
                count++;
            } else {
                continue;
            }
        }
        productGroups = baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
                        .eq(ErpSellerStoreProductGroup::getGroupId, groupId)
                        .eq(ErpSellerStoreProductGroup::getStatus, 1)
        );

        return R.ok("同步完成，当前分组中有" + productGroups.size() + "个商品，有" + count + "个商品被移出该分组");
    }


}
